package com.questionnaires.repository;

import com.questionnaires.model.Response;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ioana.ruca@gmail.com
 */
@Repository
public class ResponseRepositoryImpl implements ResponseRepository {

    @Autowired
    SessionFactory sessionFactory;

    @Transactional
    @Override
    public void saveOrUpdate(Response response) {

        sessionFactory.getCurrentSession().saveOrUpdate(response);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    @SuppressWarnings("unchecked")
    public List<Response> findAllByQuestion(long questionId) {

        Query query = sessionFactory.getCurrentSession().createQuery(
                "from Response response where response.question.id=:questionId");
        query.setLong("questionId", questionId);
        return query.list();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Response findById(long id) {

        return (Response) sessionFactory.getCurrentSession().get(Response.class, id);
    }
}
